# -*- coding: utf-8 -*-
# 'send' 处理后回复
# 'done' 终端回复确认指令
# 'stop' 终端退出登录
# 'none' 没有任何动作
import datetime
import random
import logging

from core.model import DevData, Telephone, Message, Disadmin, MessageCenter
from core.tools import LocateHandle, FamilyPush
from core.packet import now

logger = logging.getLogger('server')


def S0(conn, params):
    """
    成员绑定指令应答
    """
    try:
        dis = Disadmin.objects(dev=conn.imei).get()
    except Disadmin.DoesNotExist:
        return 'none', None
    if params[0] == '1':
        try:
            FamilyPush([dis.user.id], {'type': 'babyauthok'})
            dis.delete()
        except:
            logger.error('baby authok send mqtt error')
    else:
        try:
            FamilyPush([dis.user.id], {'type': 'babyauthno'})
            dis.delete()
        except:
            logger.error('baby authno send mqtt error')
    return 'none', None


def S1(conn, timezone):
    """
    终端登录请求
    """
    if timezone and timezone != conn.model.timezone:
        conn.new_timezone = int(timezone)
    return 'send', ['1', now(timezone), '']


def S2(conn, params):
    """
    终端发起的心跳报文
    """
    return 'send', None


def S8(conn, params):
    """
    终端应答设置时区
    """
    return 'done', None


def S13(conn, params):
    """
    终端应答实时定位上传
    """
    return 'done', None


def S14(conn, params):
    """
    终端应答定点GPS上传
    """
    return 'done', None


def S16(conn, params):
    """
    终端应答分段定时上传
    """
    return 'done', None


def S17(conn, params):
    """
    终端应答关闭定点及定时定位上传
    """
    return 'done', None


def S19(conn, params):
    """
    终端应答速拨号码设置
    """
    return 'done', None


def S20(conn, params):
    """
    终端应答白名单号码设置
    """
    return 'done', None


def S21(conn, params):
    """
    终端发起SOS指令
    """
    conn.model.sos = True
    conn.new_sos = True
    return 'send', None


def S22(conn, params):
    """
    终端关机前发送指令
    """
    return 'stop', None


def S23(conn, params):
    """
    终端应答速拨号码设置
    v1.0.7
    """
    return 'done', None


def S24(conn, params):
    """
    终端应答白名单号码设置
    v1.0.7
    """
    return 'done', None


def S29(conn, params):
    """
    终端上传定位
    """
    LocateHandle(conn, params[3], params[1], params[2])
    return 'send', None


def S35(conn, params):
    """
    终端应答通话音量等级设置
    """
    return 'done', None


def S39(conn, params):
    """
    终端应答监听设置
    """
    return 'done', None


def S40(conn, params):
    """
    终端应答取消监听
    """
    return 'done', None


def S41(conn, params):
    """
    终端应答启用静音功能
    """
    return 'done', None


def S42(conn, params):
    """
    终端应答设置响铃
    """
    return 'done', None


def S43(conn, params):
    """
    终端应答关机
    """
    return 'stop', None


def S45(conn, params):
    """
    终端应答身份信息设置
    """
    return 'done', None


def S46(conn, params):
    """
    终端应答关闭电量上传
    """
    return 'done', None


def S47(conn, params):
    """
    终端上传主叫通话时长
    """
    timing = params[0]
    Telephone(dev=conn.imei, timing=timing).save()
    return 'send', None


def S48(conn, params):
    """
    终端上传电量、计步数据和LBS
    """
    imei = conn.imei
    voltage = float(params[0])
    step = params[1]
    distance = params[2]
    calories = params[3]
    LocateHandle(conn, params[4], active=False)
    # 转换为电量百分比,小于 3.6768为 30%以下
    # 3.2V 为关机电量, 0%
    # int(63 * (voltage - 3.2))电量百分比
    # 不需要那么精确,只需要百分之10为区间
    centi_voltage = ((int(63 * (voltage - 3.2)) / 10) + 1) * 10
    if centi_voltage <= 30 and centi_voltage < conn.model.voltage:
        MessageCenter(dev=imei, type='voltage', value=str(centi_voltage)).save()
        FamilyPush(conn.model.family,
                   {'type': 'lowvoltage', 'imei': imei, 'babyname': conn.model.name, 'voltage': centi_voltage})
    conn.model.voltage = centi_voltage
    conn.new_voltage = centi_voltage
    try:
        date = datetime.date.today()
        devdata = DevData.objects(date=date, dev=imei).get()
        devdata.step = int(step)
        devdata.distance = float(distance)
        devdata.calories = float(calories)
        devdata.save()
    except DevData.DoesNotExist:
        DevData(dev=imei, step=int(step), distance=float(distance), calories=float(calories)).save()
    return 'send', None


def S50(conn, params):
    """
    终端响应服务器下发小星星
    """
    return 'done', None


def S52(conn, params):
    imei = conn.imei
    if params[0] == 'START':
        conn.data = ''
        return 'none', None
    if params[0] == 'UP':
        if conn.data_index <= int(params[1]):
            conn.data += params[2]
            conn.data_index += 1
        return 'send', ['UP', str(conn.data_index - 1)]
    if params[0] == 'END':
        audioid = random.randint(10000000000000, 99999999999999)
        Message(
            sender=imei,
            dev=imei,
            content=conn.data.encode('base64'),
            audioid=audioid,
            audiolen=int(params[1]),
            type='baby'
        ).save()
        conn.data = ''
        conn.data_index = 0

        data = {
            'type': 'newmessage',
            'data': {
                'id': str(imei),
                'type': 'baby',
                'portrait': '/static/baby/portrait/' + conn.model.imgkey + '.png',
                'audioid': audioid,
                'audiolen': params[1],
                'time': datetime.datetime.now(),
            }
        }
        FamilyPush(conn.model.family, data)
        return 'none', None


def S53(conn, params):
    """
    终端响应 S53 START END 指令
    """
    return 'done', None
